package com.imooc.intercerptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by zghgchao 2018/4/15 15:53
 * 缺点：只能拿到处理器的声明，不能拿到具体的参数值
 */
//@Component//声明成Spring的组件(由spring初始化)，若使其生效还需配置webConfig
public class TimeInterceptor implements HandlerInterceptor {
    /**
     * 在处理器handler的方法执行之前调用
     * @param httpServletRequest
     * @param httpServletResponse
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {

        System.out.println("preHandle");

        System.out.println(((HandlerMethod)handler).getBean().getClass().getName());//打印出handler的类目
        System.out.println(((HandlerMethod)handler).getMethod().getName());//打印出handler的方法名

        httpServletRequest.setAttribute("startTime",new Date().getTime());
        return true;//是否执行下面两个方法
    }

    /**
     * 在处理器handler方法执行之后调用，如果handler抛出异常，就不会调用
     * @param httpServletRequest
     * @param httpServletResponse
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println("postHandle");

        Long startTime = (Long) httpServletRequest.getAttribute("startTime");
        System.out.println("Time interceptor 耗时："+(new Date().getTime()-startTime));
    }

    /**
     * 在处理器handler方法调用后执行，不管handler是否抛出异常
     * @param httpServletRequest
     * @param httpServletResponse
     * @param handler
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) throws Exception {
        System.out.println("afterCompletion");
        Long startTime = (Long) httpServletRequest.getAttribute("startTime");
        System.out.println("Time interceptor 耗时："+(new Date().getTime()-startTime));
        System.out.println("Exception is : "+e);
    }
}
